package com.youlu.campus.service.order.impl;

import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.SFWaybillSubmitLog;
import com.youlu.campus.entity.VO.req.ShunFengOrderVO;
import com.youlu.campus.service.notify.ShunFengService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DeliveryOrderItemService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ShunFengService shunFengService;

    /**
     * 根据同步状态和发货状态获取订单发货信息
     * @param status
     * @param deliveryStatus
     * @return
     */
    public List<DeliveryOrderItem> findByStatusAndDeliveryStatus(String status,String deliveryStatus){
        Query query  = new Query();
        query.addCriteria(Criteria.where("deliveryStatus").is(deliveryStatus));
        query.addCriteria(Criteria.where("status").is(status));
        return this.mongoTemplate.find(query,DeliveryOrderItem.class);
    }



    public void doSyncSF(DeliveryOrderItem deliveryOrderItem) {
        SFWaybillSubmitLog sfWaybillSubmitLog = shunFengService.shunFengOrder(buildSFOrder(deliveryOrderItem));
        //统计条数
        statisticsTask(deliveryOrderItem.getTaskId(), "count", 1);
        if (Objects.isNull(sfWaybillSubmitLog)) {
            //统计条数
            statisticsTask(deliveryOrderItem.getTaskId(), "failCount", 1);
            updateItem(deliveryOrderItem.getId(),"",DeliveryOrderItem.FAIL);
            return;
        }
        this.mongoTemplate.save(sfWaybillSubmitLog);
        //统计条数
        statisticsTask(deliveryOrderItem.getTaskId(), "successCount", 1);
        updateItem(deliveryOrderItem.getId(),sfWaybillSubmitLog.getMailNo(),DeliveryOrderItem.SUCCESS);
        //更新订单状态
        updateOrder(deliveryOrderItem.getSubOrderNo(),sfWaybillSubmitLog.getMailNo());
    }

    /**
     * 更新订单状态为待发货
     *
     * @param subOrderNo
     * @param mailNo
     */
    @Async
    public void updateOrder(String subOrderNo,String mailNo){
        Query query = new Query();
        query.addCriteria(Criteria.where("oOrderNo").is(subOrderNo));
        OOrderInfo subOrder = this.mongoTemplate.findOne(query, OOrderInfo.class);
        if(Objects.isNull(subOrder)){
            return;
        }
        Date now = new Date();
        //更新子订单
        Update update = new Update();
        update.set("status","3");
        //update.set("expressNo",mailNo);
        //update.set("logisticsNo",mailNo);
        //update.set("logisticsCompany","EMS");
        update.set("updatedTime",now);
        this.mongoTemplate.updateFirst(query,update, OOrderInfo.class);
        query = new Query();
        query.addCriteria(Criteria.where("orderNo").is(subOrder.getOrderNo()));
        //更新主订单
        update = new Update();
        update.set("status","3");
       //update.set("logisticsNo",mailNo);
        //update.set("logisticsCompany","EMS");
        update.set("updatedTime",now);
        this.mongoTemplate.updateFirst(query,update, OrderInfo.class);
    }

    @Async
    public void updateItem(String itemId,String mailNo,String status){
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(itemId));
        Update update = new Update();
        if(StringUtils.isNotBlank(mailNo)){
            //更新订单运单号
            update.set("expressNumber",mailNo);
        }
        Date now = new Date();
        update.set("status",status);
        update.set("updatedTime",now);
        update.set("syncTime",now);
        this.mongoTemplate.updateMulti(query,update,DeliveryOrderItem.class);


    }

    @Async
    public void statisticsTask(String taskId, String property, Integer count) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(taskId));
        Update update = new Update();
        update.inc(property, count);
        this.mongoTemplate.updateFirst(query, update, DeliveryOrderTask.class);

    }

    private ShunFengOrderVO buildSFOrder(DeliveryOrderItem deliveryOrderItem) {
        ShunFengOrderVO shunFengOrder = new ShunFengOrderVO();
        shunFengOrder.setOrderId(deliveryOrderItem.getSubOrderNo());
        shunFengOrder.setDTel(deliveryOrderItem.getReceiveMobile());
        shunFengOrder.setDMobile(deliveryOrderItem.getReceiveMobile());
        shunFengOrder.setDContact(deliveryOrderItem.getReceiveName());
        shunFengOrder.setDCompany(deliveryOrderItem.getReceiveName());
        shunFengOrder.setDAddress(deliveryOrderItem.getProvince() + deliveryOrderItem.getCity() + deliveryOrderItem.getCounty() + deliveryOrderItem.getAddress());
        shunFengOrder.setJMobile("16600083199");
        shunFengOrder.setJContact("国青实践");
        shunFengOrder.setJAddress("北京市海淀区学院桥");
        List<String> remarkList = new ArrayList<>(5);
        String certificateNumber = deliveryOrderItem.getCertificateNumber();
        String itemName = deliveryOrderItem.getItemName();
        if(StringUtils.isNotBlank(itemName)){
            remarkList.add(itemName);
        }
        if(StringUtils.isNotBlank(deliveryOrderItem.getYaXian())){
            remarkList.add(deliveryOrderItem.getYaXian());
        }
        if(StringUtils.isNotBlank(deliveryOrderItem.getCaPrintName())){
            remarkList.add(deliveryOrderItem.getCaPrintName());
        }
        if(StringUtils.isNotBlank(certificateNumber)){
            remarkList.add(certificateNumber);
        }
        if(StringUtils.isNotBlank(deliveryOrderItem.getActivityName())){
            remarkList.add(deliveryOrderItem.getActivityName());
        }
        shunFengOrder.setRemark(remarkList.stream().collect(Collectors.joining(",")));
        List<Cargo> cargoList = new ArrayList<>();
        if (StringUtils.isNotBlank(deliveryOrderItem.getCertificateName())) {
            Cargo cargo = new Cargo();
            cargo.setName(deliveryOrderItem.getCertificateName());
            cargo.setCount("1");
            cargo.setUnit("本");
            cargoList.add(cargo);
        }
        if (StringUtils.isNotBlank(itemName)) {
            Cargo cargo = new Cargo();
            cargo.setName(itemName);
            cargo.setCount("1");
            cargo.setUnit("个");
            cargoList.add(cargo);
        }
        shunFengOrder.setCargoList(cargoList);
        return shunFengOrder;
    }

}
